<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">


      <el-form-item label="id" prop="id" v-if="form.id">
        <el-input v-model="form.id" placeholder="id" disabled></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="APP版本" prop="appversion">
            <el-input v-model="form.appversion" placeholder="APP版本号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="更新内容" prop="updateinfo" style="margin-right: 40px">
            <el-input v-model="form.updateinfo" :contentDefault="form.updateinfo" @child-event="parentsCont"
              type="textarea" placeholder="请输入更新内容" :autosize="{ minRows: 5 }"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">

        <el-form-item label="上传文件" prop="file" style="margin-bottom: 10px">
          <el-upload class="upload-demo" drag multiple v-model="form.file" ref="upload" :action="actionUrl" :data="form"
            :headers="headers" accept=".apk" :limit="1" :file-list="fileList" :before-upload="beforeUpload"
            :on-success="handleUploadSuccess" :auto-upload="true">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              上传文件，将文件拖到此处，或点击<em>上传文件</em>
            </div>
            <div class="el-upload__tip" slot="tip">请上传APK格式文件</div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AppversioninfoDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/appinfo/appversioninfo'
import { rule } from '/@/utils/validate';
import { Session } from '/@/utils/storage';
const emit = defineEmits(['refresh']);
// 定义变量内容
const dataFormRef = ref();
const fileList = ref();
const actionUrl = ref('/api/appinfo/appversioninfo')
const visible = ref(false)
const loading = ref(false)
const autoUpload = ref(true)
const tableLoading = ref(false)
// 定义字典

// 提交表单数据
const form = reactive({
  id: 0,
  appversion: '',
  updateinfo: '',
  updatetime: '',
  file: ''
});

const headers = computed(() => {
  return {
    Authorization: 'Bearer ' + Session.getToken(),
    'TENANT-ID': Session.getTenant(),
  };
});
// 定义校验规则
const dataRules = ref({
})

// 打开弹窗
const openDialog = (id: number) => {
  visible.value = true
  form.id = 0

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取appversioninfo信息
  if (id > 0) {
    form.id = id
    getappversioninfoData(id)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;
  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};
/**文件上传中处理 */
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  console.log('fileList', fileList);

}

// 上传成功回调
// function handleUploadSuccess(res: any, file: any) {

//   if (res.code === 0) {
//     console.log('res===', res);

//   }
// }
// 文件上传

function handleUploadSuccess(res: any, file: any, fileList: any) {
  console.log('res', res);

  tableLoading.value = false
  if (res.code == 0) {
    fileList = []
    useMessage().success('上传成功')
    visible.value = false;
    emit('refresh');
  } else {
    useMessage().error('上传出错')
  }
}
const parentsCont = (data: any) => {
  form.updateinfo = data
}
const beforeUpload = (file: File) => {
  console.log(1231231231231231);

  console.log('file', file);

  tableLoading.value = true
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
  const isType = ['apk']
  if (isType.indexOf(fileSuffix) === -1) {
    useMessage().error('上传文件只能是apk格式');
    return false
  }
  tableLoading.value = false
  console.log('file.raw', file);

  // form.file = file
  return isType
}
// 初始化表单数据
const getappversioninfoData = (id: number) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>